<template>
  <div>
    <div class="form">
      <el-form :inline="true" :model="pagination" class="demo-form-inline">
        <el-form-item label="板块名">
          <el-input
            v-model="pagination.name"
            placeholder="按 板块名 查找"
            clearable
            @clear="pagination.name = null"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createTime"
            type="daterange"
            unlink-panels
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="reloadData">开始查找</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="adding = true">添加板块</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      stripe
      border
    >
      <el-table-column label="id" width="100" prop="id"> </el-table-column>
      <el-table-column label="板块头像" width="100">
        <template #default="scope">
          <el-image :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column label="板块名称">
        <template #default="scope">
          <el-tag>{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
      <el-table-column label="帖子数量" prop="postCount" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="真的要删除吗?"
            @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 50, 100, 200]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog v-model="editing" title="编辑">
      <div class="uploader">
        <el-upload
          :headers="headers"
          :action="uploadURL"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <el-form :model="editForm" label-position="right">
        <el-form-item label="板块名称" label-width="140px">
          <el-input
            placeholder="请输入板块名称"
            v-model="editForm.name"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="editing = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateInfo"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="adding" title="添加板块">
      <el-form :model="editForm" label-position="right">
        <el-form-item label="板块名称" label-width="140px">
          <el-input
            placeholder="请输入板块名称"
            v-model="editForm.name"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="adding = false">取消</el-button>
          <el-button type="primary" @click="handleAdd"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { getLoggedUser } from "@/utils/stateUtils";
import {
  listTags,
  updateTag,
  deleteTag,
  addTag,
  uploadURL,
} from "@/api/adminAPI";
import { ElMessage } from "element-plus";

const imageUrl = ref();
const headers = { token: getLoggedUser().token };
const pagination = reactive({
  page: 1,
  size: 10,
  total: 20,
});
const tableData = ref();
const editing = ref(false);
const adding = ref(false);
const editForm = ref({});
const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "上月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "上三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const createTime = ref();

const reloadData = () => {
  listTags(pagination, createTime.value).then(({ data }) => {
    pagination.page = data.page;
    pagination.size = data.size;
    pagination.total = data.total;
    tableData.value = data.data;
  });
};

const handleSizeChange = (val) => {
  pagination.size = val;
  reloadData();
};
const handleCurrentChange = (val) => {
  pagination.page = val;
  reloadData();
};

const handleEdit = (row) => {
  editing.value = true;
  editForm.value = row;
};
const handleDelete = (row) => {
  deleteTag(row.id).then((data) => {
    ElMessage.success(data.message);
    window.location.reload();
  });
};
const handleUpdateInfo = () => {
  editing.value = false;
  updateTag(editForm.value).then((data) => {
    ElMessage.success(data.message);
    window.location.reload();
  });
};
const handleAdd = () => {
  adding.value = false;
  addTag(editForm.value).then((data) => {
    ElMessage.success(data.message);
    window.location.reload();
  });
};

const handleAvatarSuccess = (response, uploadFile) => {
  if (response.success) {
    ElMessage.success(response.message);
  } else {
    ElMessage.error(response.message);
  }
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  editForm.value.avatar = response.data;
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("支支持 jpg 或 png 格式的图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
reloadData();
</script>

<style scoped>
.pagination {
  margin-top: 20px;
}
.form {
  display: flex;
  margin-bottom: 10px;
}
.uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}
</style>
